﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace UnitTests
{
	public class TestThread
	{
		private bool isRunningInUiThread;
		private ThreadCommunicator communicator;

		public TestThread(ThreadCommunicator communicator, bool uiThread)
		{
			this.communicator = communicator;
			this.isRunningInUiThread = uiThread;
			this.IsDone = false;
		}

		public bool IsDone { get; private set; }

		private void ReportErrors(string testCaseName, string[] errors, int testId)
		{
			bool pass = errors.Length == 0;
			this.communicator.AddMessage("[" + testCaseName + "] " + (pass ? "PASS" : "FAIL"), pass, testId);

			foreach (string error in errors)
			{
				this.communicator.AddMessage(error, false, 0);
			}
		}

		public void Go()
		{
			TestCaseBase testCase = null;
			if (this.isRunningInUiThread)
			{
				testCase = TestRegistry.PopTestCase(true);
				if (testCase == null)
				{
					testCase = TestRegistry.PopTestCase(false);
				}

				if (testCase != null)
				{
					testCase.DoTest();
					this.ReportErrors(testCase.Name, testCase.ErrorMessages, testCase.TestCaseID);
				}
				else
				{
					this.IsDone = true;
				}
			}
			else
			{
				while (true)
				{
					testCase = TestRegistry.PopTestCase(false);
					if (testCase == null)
					{
						this.IsDone = true;
						break;
					}

					bool pass = testCase.DoTest();
					if (!pass)
					{
						this.ReportErrors(testCase.Name, testCase.ErrorMessages, testCase.TestCaseID);
					}
				}
			}
		}
	}
}
